package com.foreknow.test_IO;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentMethods {
    public String write(List<Student> list) {
        FileWriter fw;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter("IO/student.txt");
            bw = new BufferedWriter(fw);
            for (Student student : list) {
                bw.write(student.toString());
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                assert bw != null;
                bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "IO/student.txt";
    }

    public List read(String string) {
        FileReader fr;
        BufferedReader br;
        List<Student> list = new ArrayList<>();
        try {
            fr = new FileReader(string);
            br = new BufferedReader(fr);
            String string1 = br.readLine();
            while (string1 != null) {
                String[] strings = string1.split(",");
                Student student = new Student(strings[0], strings[1], strings[2], strings[3]);
                list.add(student);
                string1 = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}